<script setup lang="ts">
  import {
    ArrowDown,
    CircleCheck,
    Delete,
    Search,
    Warning,
    RefreshRight,
  } from '@element-plus/icons-vue'
  import { PropType, ref } from 'vue'
  import { useRouter } from 'vue-router'
  import { useGetAllGoodTypeOptions } from '@/services/pages/good/useType'
  import {
    useGoodSettlesDel,
    useGoodSettlesEnable,
    useGoodSettlesDisable,
  } from '@/services/pages/order/useGoodSettle'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import infoTip from '@/config/info-tip'
  import { ElMessageBox } from 'element-plus'

  const { del } = useGoodSettlesDel()
  const { disable } = useGoodSettlesDisable()
  const { enable } = useGoodSettlesEnable()
  const { options, getOptions } = useGetAllGoodTypeOptions()

  defineOptions({
    name: 'HeaderGoodSettleSet',
  })

  const props = defineProps({
    settleIds: {
      type: Array as PropType<Array<string>>,
      default: () => [],
    },
  })

  const emits = defineEmits<{
    (e: 'update', value: typeof searchForm.value): void
  }>()

  const router = useRouter()
  const cascaderProps = {
    checkStrictly: true,
    label: 'name',
    value: 'id',
    children: 'childData',
  }
  const searchForm = ref<Omit<OrderAPIRequest.GoodSettles, 'limit' | 'page'>>({
    goodsKeyword: '',
    goodsOneTypeId: '',
    goodsThreeTypeId: '',
    goodsTwoTypeId: '',
    name: '',
  })
  const typeIds = ref<Array<string>>([])

  const createCommoditySettleBtnClick = () => {
    router.push({ path: '/order/good/settle/create' })
  }

  const handleSelectGoodType = (value: Array<string>) => {
    Object.assign(searchForm.value, {
      goodsOneTypeId: '',
      goodsThreeTypeId: '',
      goodsTwoTypeId: '',
    })

    if (!value) {
      getList()
      return
    }

    if (value.length === 1) {
      searchForm.value.goodsOneTypeId = value[0]
    }

    if (value.length === 2) {
      searchForm.value.goodsOneTypeId = value[0]
      searchForm.value.goodsTwoTypeId = value[1]
    }

    if (value.length === 3) {
      searchForm.value.goodsOneTypeId = value[0]
      searchForm.value.goodsTwoTypeId = value[1]
      searchForm.value.goodsThreeTypeId = value[2]
    }
    getList()
  }

  const reset = () => {
    searchForm.value = {
      goodsKeyword: '',
      goodsOneTypeId: '',
      goodsThreeTypeId: '',
      goodsTwoTypeId: '',
      name: '',
    }
    typeIds.value = []
    getList()
  }

  const getList = () => {
    emits('update', { ...searchForm.value })
  }

  const handleMultipleOperate = (type: 'del' | 'disable' | 'enable') => {
    if (props.settleIds.length === 0) {
      HMessageBox.error(infoTip.order.goodSettle.no_select_good_settle)
      return
    }

    const msgOption = {
      del: infoTip.order.goodSettle.multiple_del,
      enable: infoTip.order.goodSettle.multiple_enable,
      disable: infoTip.order.goodSettle.multiple_disable,
    }

    ElMessageBox({
      title: '提示',
      message: msgOption[type],
      type: type === 'del' ? 'error' : 'warning',
      showCancelButton: true,
      async beforeClose(action, instance, done) {
        if (['close', 'cancel'].includes(action)) {
          done()
          return
        }

        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.cancelButtonLoading = true
          let res: APIResponse | null = null
          switch (type) {
            case 'del':
              res = await del(props.settleIds)
              break
            case 'disable':
              res = await disable(props.settleIds)
              break
            case 'enable':
              res = await enable(props.settleIds)
              break
          }
          instance.confirmButtonLoading = false
          instance.cancelButtonLoading = false
          if (res.code === 20000) {
            const successMsgOption = {
              del: infoTip.order.goodSettle.del_success,
              enable: infoTip.order.goodSettle.multiple_enable_success,
              disable: infoTip.order.goodSettle.multiple_disable_success,
            }
            HMessage.success(successMsgOption[type])
            getList()
            done()
            return
          }

          HMessageBox.error(res.message)
        }
      },
    })
  }

  defineExpose({
    getGoodTypeOptions: getOptions,
  })
</script>

<template>
  <div class="header-commodity-settle-set">
    <div class="btn-group">
      <h-plain-button @click="createCommoditySettleBtnClick"> 添加设备结算 </h-plain-button>
      <el-dropdown trigger="click">
        <h-button :disabled="props.settleIds.length === 0">
          批量操作
          <el-icon>
            <ArrowDown />
          </el-icon>
        </h-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="handleMultipleOperate('enable')">
              <el-icon>
                <CircleCheck />
              </el-icon>
              批量启用
            </el-dropdown-item>
            <el-dropdown-item @click="handleMultipleOperate('disable')">
              <el-icon>
                <Warning />
              </el-icon>
              批量禁用
            </el-dropdown-item>
            <el-dropdown-item @click="handleMultipleOperate('del')">
              <el-icon>
                <Delete />
              </el-icon>
              批量删除
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    <div class="search">
      <el-input
        v-model.trim="searchForm.name"
        placeholder="请输入方案名称"
        clearable
        class="name"
        @keyup.enter="getList"
        @clear="getList"
      />
      <el-input
        v-model.trim="searchForm.goodsKeyword"
        placeholder="请输入设备名称/设备编号"
        clearable
        class="good"
        @keyup.enter="getList"
        @clear="getList"
      />
      <el-cascader
        v-model="typeIds"
        :options="options"
        :props="cascaderProps"
        class="good-type"
        clearable
        placeholder="请选择设备分类"
        @change="handleSelectGoodType"
        @clear="getList"
      ></el-cascader>
      <h-button type="primary" @click="getList">
        <el-icon>
          <Search />
        </el-icon>
        搜索
      </h-button>
      <h-button @click="reset">
        <el-icon>
          <RefreshRight />
        </el-icon>
        重置
      </h-button>
    </div>
  </div>
</template>

<style scoped lang="scss">
  .header-commodity-settle-set {
    display: flex;
    justify-content: space-between;

    .btn-group {
      display: flex;
      column-gap: 5px;
    }

    .search {
      display: flex;
      column-gap: 5px;

      .name {
        width: 120px;
      }

      .good {
        width: 160px;
      }

      :deep(.good-type) {
        width: 180px;
      }
    }
  }
</style>
